package com.xyulu.config.shiro;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xyulu.entity.SysUserEntity;
import com.xyulu.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author Xyulu
 * @Date 2021/1/30 21:35
 * @Version 1.0
 */
@Slf4j
public class CustomerRealm extends AuthorizingRealm {
    @Resource
    private SysUserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String) principals.getPrimaryPrincipal();
        log.info("调用授权方法，验证:"+username);
        List<String> roles = userService.getRoleNameByLogin(username);
        if (!CollectionUtils.isEmpty(roles)) {
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            roles.forEach(x->{
                //身份信息
                simpleAuthorizationInfo.addRole(x);
                //权限信息 todo
            });
            return simpleAuthorizationInfo;
        }
        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        SysUserEntity user = userService.
                getOne(Wrappers.<SysUserEntity>lambdaQuery().eq(SysUserEntity::getPhone, username));
        if (user == null){
            throw new UnknownAccountException();
        }
        //用户锁定 ToDo
        return new SimpleAuthenticationInfo(user.getPhone(),user.getPassword(),
                ByteSource.Util.bytes(user.getSalt()),this.getName());
    }
}
